"use strict";

var express = require('express');
var UUID = require('uuid')
var dt = require('date-utils')
var util = require('util')
var MyUtils = require('./../../util/utils')
var DeleteAction = require('./delete-app')

var connection = require('./../../constant/mysqlconnection').connection

var router = express.Router()
var myUtils = new MyUtils()

router.post('/createApp', function (req, res, next) {
    // 判断用户是否注册
    // 判断当前包名是否已经被占用
    var searchSql = 'select usr.user_id , app.bundle_id, app.logic_delete_flag from user usr left join application app on ' +
        'usr.user_id = app.user_id where usr.logic_delete_flag = 01 and usr.user_id = ?'
    var searchSqlParams = [
        req.body.userId
    ]
    connection.query(searchSql, searchSqlParams, function (error, results) {
        if (!error) {

            if (results.length == 0) {
                var bizFailureModel = myUtils.generateSuccess()
                bizFailureModel.model = {
                    success: 1,
                    info: '请先注册，然后再创建应用'
                }
                res.end(JSON.stringify(bizFailureModel))
            } else {
                if (isAllowCreateApp(results, req)) {
                    next('route')
                } else {
                    var bizFailureModel = myUtils.generateSuccess()
                    bizFailureModel.model = {
                        success: 2,
                        info: '包名重复，请重新填写'
                    }
                    res.end(JSON.stringify(bizFailureModel))
                }
            }
        } else {
            res.end(JSON.stringify(myUtils.generateInnerError()))
        }
    })
})

function isAllowCreateApp(results, req) {
    for (var i = 0, len = results.length; i < len; i++) {
        if (results[i].bundle_id != null && results[i].bundle_id === req.body.packageName && results[i].logic_delete_flag === '01') {
            // 说明当前应用已经被创建了
            return false
        }
    }
    return true
}

router.post('/createApp', function (req, res) {
    var insertSql = 'INSERT INTO application(id,user_id,app_name,bundle_id,app_type,description,create_time,logic_delete_flag) VALUES(?,?,?,?,?,?,?,\'01\')'
    var currentId = UUID.v1()
    var insertSqlParams = [
        currentId,
        req.body.userId,
        req.body.appName,
        req.body.packageName,
        req.body.appType,
        req.body.description,
        new Date().toFormat('YYYY-MM-DD HH24:MI:SS'),
    ]
    connection.query(insertSql, insertSqlParams, function (err, result) {
        if (!err) {
            // 创建成功
            var bizSucModel = myUtils.generateSuccess()
            bizSucModel.model = {
                success: 0,
                info: '创建成功',
                applicationId: currentId
            }
            res.end(JSON.stringify(bizSucModel))
        } else {
            console.log(err)
            res.end(JSON.stringify(myUtils.generateInnerError()))
        }
    })
})

router.get('/applist', function (req, res) {
    // 暂不做分页逻辑
    var searchSql = 'SELECT id,app_name,bundle_id,app_type,description,create_time FROM application WHERE logic_delete_flag = 01 AND user_id = ? ORDER BY create_time DESC'
    var searchSqlParam = [req.query.userId]
    connection.query(searchSql, searchSqlParam, function (err, results) {
        if (!err) {
            var bizSucModel = myUtils.generateSuccess()
            bizSucModel.model = {
                success: 0,
                applist: results
            }
            res.end(JSON.stringify(bizSucModel))
        } else {
            console.log(err)
            res.end(myUtils.generateInnerError())
        }
    })
})

var deleteAction = new DeleteAction()

router.delete('/deleteApp', function (req, res) {
    deleteAction.deleteApp(req, res)
})

router.get('/getAppInfo', function (req, res) {
    var searchSql = 'select * from application where logic_delete_flag = 01 and id = ?'
    var searchSqlParam = [
        req.query.appId
    ]
    connection.query(searchSql, searchSqlParam, function (error, results) {
        if (!error) {
            var bizSucModel = myUtils.generateSuccess()
            if (results.length == 0) {
                bizSucModel.model = {
                    success: 1,
                    info: 'app 不存在'
                }
            } else {
                bizSucModel.model = {
                    success: 0,
                    appInfo: results[0],
                    info: '查询成功',
                }
            }
            res.end(JSON.stringify(bizSucModel))
        } else {
            res.end(JSON.stringify(myUtils.generateInnerError()))
        }
    })
})

module.exports = router







